<template>
  <div class="app-container" v-loading="loading">
    <el-form
      :model="form"
      ref="formRef"
      :inline="true"
      :rules="rules"
      label-width="135px"
      :disabled="parentType == 'view'"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="工厂" prop="factoryName">
            {{ form.factoryName }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工段" prop="workshopName">
            {{ form.workshopName }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产线" prop="productLineName">
            {{ form.productLineName }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工艺段" prop="sectionName">
            {{ form.sectionName }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产日期" prop="prodDate">
            {{ form.prodDate }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="班次" prop="scheduleName">
            {{ form.scheduleName }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开始生产时间" prop="startProdTime">
            <el-time-picker
              v-model="form.startProdTime"
              clearable
              value-format="HH:mm:ss"
              placeholder="请选择开始生产时间"
              style="width: 150px"
              @change="getTimeDiffChange"
            ></el-time-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="parentType == 'handover'">
          <el-form-item label="结束生产时间" prop="endProdTime">
            <el-time-picker
              v-model="form.endProdTime"
              clearable
              value-format="HH:mm:ss"
              placeholder="请选择结束生产时间"
              style="width: 150px"
              @change="getTimeDiffChange"
            ></el-time-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="parentType == 'handover'">
          <el-form-item label="计划停机时长" prop="planShutdownDuration">
            <el-input-number
              v-model="form.planShutdownDuration"
              placeholder="请输入计划停机时长"
              :min="0"
              :max="1000000000"
              :precision="0"
              clearable
              style="width: 150px"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="生产订单" prop="workOrderList" style="width: 98%">
            <el-table :data="form.workOrderList" border style="width: 100%; margin-top: 10px">
              <el-table-column label="订单编号" prop="orderCode" width="140" />
              <el-table-column label="产品编号" prop="prodCode" />
              <el-table-column label="产品名称" prop="prodName" />
              <el-table-column label="计划产量" prop="planNumber" />
              <el-table-column label="已完工产量" prop="actualNumber" />
              <el-table-column label="完成率" prop="finishRate">
                <template #default="scope">
                  <span
                    :class="Number(scope.row.finishRate.replace('%', '')) > 100 ? 'green' : 'red'"
                  >
                    {{ scope.row.finishRate }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="单位" prop="unit" />
              <el-table-column label="计划开始时间" prop="planStartTime">
                <template #default="scope">
                  <span>{{ scope.row.planStartTime }}</span>
                </template>
              </el-table-column>
              <el-table-column label="计划结束时间" prop="planEndTime">
                <template #default="scope">
                  <span>{{ scope.row.planEndTime }}</span>
                </template>
              </el-table-column>
              <el-table-column label="工艺段" prop="sectionName" />
              <el-table-column label="来源" prop="source">
                <template #default="scope">
                  <dict-tag :options="order_source" :value="scope.row.source" />
                </template>
              </el-table-column>
              <el-table-column label="状态" prop="status">
                <template #default="scope">
                  <dict-tag :options="work_order_status" :value="scope.row.status" />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="previousClasses" v-if="parentType == 'update'">
      <div>上一班信息</div>
      <previousClassTable
        ref="previousClassTableRef"
        :datas="form"
        @handleClickPrevious="handleClickPrevious"
      ></previousClassTable>
    </div>
    <div class="previousClasses" v-if="parentType == 'update'">
      <div>
        <span>当班人员安排</span>
      </div>
      <onDutyPersonnel
        ref="onDutyPersonnelRef"
        v-model="prodChangeShiftsMemberList"
        v-if="prodChangeShiftsMemberList && prodChangeShiftsMemberList.length > 0"
        :parentType="parentType"
        :isShowProdHours="'no'"
      ></onDutyPersonnel>
    </div>

    <div class="previousClasses" v-if="parentType == 'handover' && !loading">
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane class="star" label="生产指标" name="first">
          <template #label>
            <span style="color: #f84224">*&nbsp;</span>
            生产指标
          </template>
          <productionIndicators ref="productionInRef" :datas="workgroupInfo"></productionIndicators>
        </el-tab-pane>
        <el-tab-pane class="star" label="当班人员安排" name="second">
          <template #label>
            <span style="color: #f84224">*&nbsp;</span>
            当班人员安排
          </template>
          <onDutyPersonnel
            ref="onDutyPersonnelRef"
            v-model="prodChangeShiftsMemberList"
            v-if="prodChangeShiftsMemberList && prodChangeShiftsMemberList.length > 0"
            :parentType="parentType"
            :isShowProdHours="'yes'"
            :prodHoursOriginal="prodHoursOriginal"
          ></onDutyPersonnel>
        </el-tab-pane>
        <el-tab-pane label="生产记录" name="third">
          <productionRecords
            v-if="activeName == 'third'"
            :workgroup="workgroupInfo"
          ></productionRecords>
        </el-tab-pane>
        <!--  <el-tab-pane label="设备运行情况" name="fourth">
          <equipmentOperation :datas="productionData"></equipmentOperation>
        </el-tab-pane> -->
        <el-tab-pane label="岗位交接日志" name="fifth">
          <!-- <workstationLog :datas="productionData"></workstationLog> -->
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup name="changeShifts">
import {
  getProdChangeShiftsDetail,
  shiftHandover,
  editCarryOn,
} from "@/api/productionMgt/changeShifts";
import { listShiftGroup } from "@/api/base/plan/shiftMgt/shiftGroup";
import { planGroupDetail } from "@/api/base/plan/shiftMgt/shiftGroup";
import { getFactoryTree } from "@/api/system/dept";
import { getScheduleNames4ChangeShifts } from "@/api/base/plan/shiftMgt/shiftCalendar";
// import workOrderList from "./workOrderList";
import productionIndicators from "./components/productionIndicators";
import onDutyPersonnel from "./components/onDutyPersonnel";
// import equipmentOperation from "./components/equipmentOperation";
// import workstationLog from "./components/workstationLog";
import DetailData from "./data";
import productionRecords from "./components/productionRecords";
import previousClassTable from "./components/previousClassTable";
import { ref, toRefs, reactive, useAttrs, getCurrentInstance, onMounted, nextTick } from "vue";
const attrs = useAttrs();
const { proxy } = getCurrentInstance();
const parentType = ref("add");
const workGroupOptions = ref([]);
const planGroupDetailList = ref([]);
const { work_order_status } = proxy.useDict("work_order_status");
const { order_source } = proxy.useDict("order_source");
const loading = ref(false);
// const openWorkOrder = ref(false);
const productionData = ref({});
const workgroupInfo = ref();
const activeName = ref("first");

const prodChangeShiftsMemberList = ref([]);
const prodHoursOriginal = ref();
var factoryOptions = ref([]);
var workshopOptions = ref([]);
var lineOptions = ref([]);
var processOptions = ref([]);
const emit = defineEmits(["close", "setTitle", "setActions", "setIsActionTop"]);
const actions = ref([
  {
    text: "取 消",
    theme: "",
    handle: () => {
      cancel();
    },
  },
  {
    text: "确 定",
    theme: "primary",
    handle: () => {
      submitForm();
    },
    loading: false,
  },
]);

const data = reactive({
  form: {},
  rules: {
    startProdTime: [{ required: true, message: "开始生产时间不能为空", trigger: "change" }],
    endProdTime: [{ required: true, message: "结束生产时间不能为空", trigger: "change" }],
    planShutdownDuration: [{ required: true, message: "计划停机时长不能为空", trigger: "blur" }],
  },
});

const { form, rules } = toRefs(data);

function getDetail(id) {
  loading.value = true;
  getProdChangeShiftsDetail(id)
    .then((res) => {
      form.value = res.data;
      form.value.sectionCode = form.value.sectionCode.split(",");
      form.value.workOrderList = [res.data.prodOrderDto];
      // 上一班信息
      form.value.previousClassInfo = [res.data.previousClassInfo];
      // 生产指标
      productionData.value = res.data;
      workgroupInfo.value = res.data;

      productionData.value.parentType = parentType.value;

      // 班组下拉列表
      getWorkGroupData();
      // 本班人员安排-1.先获取对应工艺段下面的班组；2.获取班组下面的本班人员
      getPlanGroupDetail();
      // 为了获取结束时间
      getScheduleNames4ChangeShiftsFun();
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}

function getPlanGroupDetail() {
  planGroupDetail({ section: form.value.sectionCode.toString() }).then((res) => {
    planGroupDetailList.value = res.data;
    nextTick(() => {
      // 根据开始生产时间、结束生产时间计算---当班人员安排--列表生产时长
      if (form.value.startProdTime && form.value.endProdTime) {
        let _prodHours = getTimeDifference();
        if (_prodHours) {
          for (let i in res.data) {
            for (let j in res.data[i].planGroupList) {
              let _ele = res.data[i].planGroupList[j];
              if (_ele.planGroupMemberList && _ele.planGroupMemberList?.length) {
                let _ar = _ele.planGroupMemberList;
                for (let n in _ar) {
                  _ar[n].prodHoursOriginal = _prodHours;
                }
              }
            }
          }
          // 新增时默认选中的班组列表--在当前页面回填时，同时获取生产时长
          form.value.prodChangeShiftsMemberList.forEach((element) => {
            element.prodHoursOriginal = _prodHours;
          });
          handleProdChangeShiftsMemberList(res.data);
        }
      } else {
        handleProdChangeShiftsMemberList(res.data);
      }
    });
  });
}

function handleProdChangeShiftsMemberList(workGropList) {
  prodChangeShiftsMemberList.value[0] = {
    sectionCode: form.value.sectionCode,
    sectionName: form.value.sectionName,
    workGroupCode: form.value.workGroup,
  };
  prodChangeShiftsMemberList.value[0].planGroupList = [];
  prodChangeShiftsMemberList.value[0].planGroupMemberList = [];
  prodChangeShiftsMemberList.value[0].planGroupList = workGropList[0].planGroupList;
  // 修复交班时切换选择班组后，班组下的岗位详情错乱展示问题
  for (let i in prodChangeShiftsMemberList.value[0].planGroupList) {
    let ele = prodChangeShiftsMemberList.value[0].planGroupList[i];
    if (form.value.workGroup == ele.workGroup) {
      ele.planGroupMemberList = form.value.prodChangeShiftsMemberList;
      prodChangeShiftsMemberList.value[0].planGroupMemberList =
        form.value.prodChangeShiftsMemberList;
    }
  }
  // prodChangeShiftsMemberList.value[0].planGroupList[0].planGroupMemberList = [
  //   ...form.value.prodChangeShiftsMemberList,
  // ];
  // prodChangeShiftsMemberList.value[0].planGroupMemberList = [
  //   ...form.value.prodChangeShiftsMemberList,
  // ];
}
function getTimeDiffChange() {
  if (form.value.startProdTime && form.value.endProdTime) {
    let _prodHours = getTimeDifference();
    for (let i in planGroupDetailList.value) {
      for (let j in planGroupDetailList.value[i].planGroupList) {
        let _ele = planGroupDetailList.value[i].planGroupList[j];
        if (_ele.planGroupMemberList && _ele.planGroupMemberList?.length) {
          let _ar = _ele.planGroupMemberList;
          for (let n in _ar) {
            _ar[n].prodHoursOriginal = _prodHours;
          }
        }
      }
    }
    handleProdChangeShiftsMemberList(planGroupDetailList.value);
  }
}
// 根据开始生产时间、结束生产时间计算生产时长
function getTimeDifference() {
  let sTime = form.value.startProdTime;
  let eTime = form.value.endProdTime;
  let _sTime = new Date("1970-01-01 " + sTime).getTime();
  let _eTime = new Date("1970-01-01 " + eTime).getTime();
  let _prodHours = null;
  if (_eTime < _sTime) {
    _eTime = _eTime + 3600000 * 24;
  }
  if (sTime && eTime) {
    let times = _eTime - _sTime;
    _prodHours = parseFloat((times / 3600000).toFixed(2));
    prodHoursOriginal.value = _prodHours;
  }
  return _prodHours;
}

function handleTabClick() {}

// 根据所选工艺段、所选生产日期、工厂id后查询获取获取-班次列表
function getScheduleNames4ChangeShiftsFun() {
  const _prodDate = form.value.prodDate;
  const yearStr = _prodDate.substring(0, 4);
  const monthStr = _prodDate.substring(5, 7);
  const dayNo = _prodDate.substring(8);
  const deptId =
    factoryOptions.value.find((item) => {
      return item.deptCode == form.value.factory;
    })?.deptId || "";
  getScheduleNames4ChangeShifts({
    sectionCodeList: form.value.sectionCode,
    yearStr,
    monthStr,
    dayNo,
    deptId,
  })
    .then((res) => {
      form.value.endProdTime =
        res.data.find((item) => {
          return item.classesCode == form.value.classesCode;
        })?.endTime || "";
    })
    .catch(() => {
      proxy.$modal.msgError("当前工艺段无排班计划，请设置后再接班");
    });
}

function getWorkGroupData() {
  listShiftGroup({ sectionCode: form.value.sectionCode.toString() }).then((res) => {
    workGroupOptions.value = res.rows;
  });
}

function cancel() {
  emit("close");
}

function submitForm() {
  if (parentType.value == "update") {
    proxy.$refs["formRef"].validate((valid) => {
      if (valid) {
        handleUpdateSubmit();
      }
    });
  }
  if (parentType.value == "handover") {
    // 1.验证当前表单
    proxy.$refs["formRef"].validate((valid) => {
      if (valid) {
        // 3.验证当班人员安排
        proxy.$refs["onDutyPersonnelRef"].$refs["formRefDuty"].validate((valid) => {
          if (valid) {
            handleHandoverSubmit();
          } else {
            proxy.$modal.msgError("当班人员安排列表生产工时不能为空！");
          }
        });
      }
    });
  }
}

function handleUpdateSubmit() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      for (let i in prodChangeShiftsMemberList.value) {
        let el = prodChangeShiftsMemberList.value[i];
        for (let j in el.planGroupMemberList) {
          if (!el.planGroupMemberList[j].workStationStaffName) {
            proxy.$modal.msgError(`第${Number(i) + 1}组第${Number(j) + 1}行岗位人员没有填写！`);
            return;
          }
        }
      }
      loading.value = true;
      let newList = {};
      newList.factory = form.value.factory;
      newList.factoryName =
        factoryOptions.value.find((item) => {
          return item.deptCode == form.value.factory;
        })?.deptName || "";
      newList.workshopCode = form.value.workshopCode;
      newList.workshopName =
        workshopOptions.value.find((item) => {
          return item.deptCode == form.value.workshopCode;
        })?.deptName || "";
      newList.productLine = form.value.productLine;
      newList.productLineName =
        lineOptions.value.find((item) => {
          return item.deptCode == form.value.productLine;
        })?.deptName || "";
      newList.sectionCode = form.value.sectionCode.toString();
      newList.sectionName = processOptions.value
        .map((item) => {
          if (form.value.sectionCode.includes(item.deptCode)) {
            return item.deptName;
          }
        })
        .toString();
      newList.prodDate = form.value.prodDate;
      newList.scheduleName = form.value.scheduleName;
      newList.classesCode = form.value.classesCode;
      newList.startProdTime = form.value.startProdTime;
      newList.workGroup = form.value.workGroup;
      newList.workOrderCodeList = form.value.workOrderList.map((item) => {
        return item.orderCode;
      });
      let _arr = proxy.$refs?.onDutyPersonnelRef?.form?.tableData || [];
      newList.prodChangeShiftsMemberList = _arr.map((item) => {
        let _arr = item.planGroupMemberList.map((items) => {
          return {
            ...items,
            sectionCode: item.sectionCode.toString(),
            sectionName: item.sectionName,
          };
        });
        return {
          ...item,
          sectionCode: item.sectionCode.toString(),
          prodMemberDtoList: _arr,
          workGroupName:
            item.planGroupList.find((its) => {
              return its.workGroup == item.workGroupCode;
            })?.workGroupName || "",
        };
      });
      if (form.value.id) {
        newList.id = form.value.id;
        editCarryOn(newList)
          .then(() => {
            proxy.$modal.msgSuccess("编辑成功");
            cancel();
          })
          .catch(() => {
            loading.value = true;
          });
      }
    }
  });
}

function handleHandoverSubmit() {
  loading.value = true;
  let newList = {};
  newList.factory = form.value.factory;
  newList.factoryName =
    factoryOptions.value.find((item) => {
      return item.deptCode == form.value.factory;
    })?.deptName || "";
  newList.workshopCode = form.value.workshopCode;
  newList.workshopName =
    workshopOptions.value.find((item) => {
      return item.deptCode == form.value.workshopCode;
    })?.deptName || "";
  newList.productLine = form.value.productLine;
  newList.productLineName =
    lineOptions.value.find((item) => {
      return item.deptCode == form.value.productLine;
    })?.deptName || "";
  newList.sectionCode = form.value.sectionCode.toString();
  newList.sectionName = processOptions.value
    .map((item) => {
      if (form.value.sectionCode.includes(item.deptCode)) {
        return item.deptName;
      }
    })
    .toString();
  newList.prodDate = form.value.prodDate;
  newList.scheduleName = form.value.scheduleName;
  // newList.scheduleName =
  //   shiftGroupsList.value.find((item) => {
  //     return item.scheduleName == form.value.scheduleName;
  //   })?.scheduleName || "";
  newList.startProdTime = form.value.startProdTime;
  newList.endProdTime = form.value.endProdTime;
  newList.workGroup = form.value.workGroup;
  newList.workOrderCodeList = form.value.workOrderList.map((item) => {
    return item.workOrderCode;
  });
  newList.prodIndexType = productionData?.value?.prodIndexType || 1;
  if (newList.prodIndexType == 1) {
    newList.prodIndexCastFilmDto = proxy.$refs?.productionInRef?.castingTableData[0] || {};
  } else if (newList.prodIndexType == 2) {
    newList.prodIndexRollDto = proxy.$refs?.productionInRef?.rollTableData[0] || {};
  } else if (newList.prodIndexType == 3) {
    newList.prodIndexWaterVaporDto = proxy.$refs?.productionInRef?.waterVaporTableData[0] || {};
  }

  let _arr = proxy.$refs?.onDutyPersonnelRef?.form?.tableData || [];
  newList.prodChangeShiftsMemberList = _arr.map((item) => {
    let _arr = item.planGroupMemberList.map((items) => {
      return {
        ...items,
        sectionCode: item.sectionCode.toString(),
        sectionName: item.sectionName,
      };
    });
    return {
      ...item,
      sectionCode: item.sectionCode.toString(),
      prodMemberDtoList: _arr,
      workGroupName:
        item.planGroupList.find((its) => {
          return its.workGroup == item.workGroupCode;
        })?.workGroupName || "",
    };
  });

  newList.id = form.value.id;
  shiftHandover(newList).then(() => {
    proxy.$modal.msgSuccess("交班成功");
    cancel();
  });
}

function handleClickPrevious(row) {
  proxy.subPage(DetailData, { title: "交班详情", data: row });
}

// 获取工厂列表
function getFactorys(query) {
  getFactoryTree(query).then((res) => {
    factoryOptions.value = res.data;
  });
}
getFactorys();
onMounted(async () => {
  const { data } = attrs;
  parentType.value = data.parentType;
  if (data?.id) {
    getDetail(data.id);
  }

  if (parentType.value == "view") {
    actions.value = [
      {
        text: "取 消",
        theme: "",
        handle: () => {
          cancel();
        },
      },
    ];
    emit("setActions", actions.value);
  } else {
    actions.value = [
      {
        text: "取 消",
        theme: "",
        handle: () => {
          cancel();
        },
      },
      {
        text: "确 定",
        theme: "primary",
        handle: () => {
          submitForm();
        },
        loading: false,
      },
    ];
    emit("setActions", actions.value);
  }
});
</script>
<style lang="scss" scoped>
.previousClasses {
  margin-top: 20px;
}

.star {
  .el-tabs__item::after {
    margin-left: 5px;
    color: red;
    content: "*";
  }
}

.green {
  color: green;
}

.red {
  color: red;
}
</style>
